package com.example.chenz.graceplayer;

import android.app.Activity;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.chenz.data.Music;
import com.example.chenz.data.MusicList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends Activity {

    private ImageButton imageButton_previous;
    private ImageButton imageButton_playOrPause;
    private ImageButton imageButton_stop;
    private ImageButton imageButton_next;
    private ListView listView;

    //歌曲列表对象
    private ArrayList<Music> musicArrayList;

    private int number = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicFile();
    }

    public void findViews() {
        imageButton_previous = (ImageButton)findViewById(R.id.imageButton_previous);
        imageButton_playOrPause = (ImageButton)findViewById(R.id.imageButton_play);
        imageButton_stop = (ImageButton)findViewById(R.id.imageButton_stop);
        imageButton_next = (ImageButton)findViewById(R.id.imageButton_next);
        listView = (ListView)findViewById(R.id.listView);
    }

    public void registerListeners() {
        imageButton_previous.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                moveNumberToPrevious();
                play(number);
                imageButton_playOrPause.setBackgroundResource(R.drawable.button_pause);
            }
        });

        imageButton_playOrPause.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    pause();
                    imageButton_playOrPause.setBackgroundResource(R.drawable.button_pause);
                }else {
                    play(number);
                    imageButton_playOrPause.setBackgroundResource(R.drawable.button_play);
                }
            }
        });

        imageButton_stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stop();
                imageButton_playOrPause.setBackgroundResource(R.drawable.button_play);
            }
        });

        imageButton_next.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                moveNumberToNext();
                play(number);
                imageButton_playOrPause.setBackgroundResource(R.drawable.button_pause);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number = position;
                play(number);
                imageButton_playOrPause.setBackgroundResource(R.drawable.button_pause);
            }
        });
    }

    private void initMusicList() {
        musicArrayList = MusicList.getMusicArrayList();

        //避免重复添加音乐
        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME},null,null,
                    MediaStore.Audio.AudioColumns.TITLE);

            if (mMusicCursor != null) {
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
                int indexDuration = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);

                for (mMusicCursor.moveToFirst();!mMusicCursor.isAfterLast();mMusicCursor.moveToNext()) {
                    String stringTitle = mMusicCursor.getString(indexTitle);
                    String stringArtist = mMusicCursor.getString(indexArtist);
                    String stringPath = mMusicCursor.getString(indexPath);
                    String stringDuration = mMusicCursor.getString(indexDuration);

                    if (stringArtist.equals("<unknown>"))
                        stringArtist = "艺术家未知";

                    Music music = new Music(stringTitle,stringArtist,stringPath,stringDuration);
                    musicArrayList.add(music);
                }
            }

        }
    }

    //设置适配器并初始化listView
    private void initListView() {
        List<Map<String,String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String,String> map;
        SimpleAdapter simpleAdapter;
        for (Music music:musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName",music.getMusicName());
            map.put("musicArtist",music.getMusicArtist());
            list_map.add(map);
        }

        String[] from = new String[] {"musicName","musicArtist"};
        int[] to = {R.id.listview_tv_title_item,R.id.listview_tv_artist_item};

        simpleAdapter = new SimpleAdapter(this,list_map,R.layout.listview,from,to);
        listView.setAdapter(simpleAdapter);
    }

    private void checkMusicFile() {
        if (musicArrayList.isEmpty()) {
            imageButton_previous.setEnabled(false);
            imageButton_playOrPause.setEnabled(false);
            imageButton_stop.setEnabled(false);
            imageButton_next.setEnabled(false);
            Toast.makeText(getApplicationContext(),R.string.none_music,Toast.LENGTH_SHORT).show();
        }else {
            imageButton_previous.setEnabled(true);
            imageButton_playOrPause.setEnabled(true);
            imageButton_stop.setEnabled(true);
            imageButton_next.setEnabled(true);
        }
    }

    private MediaPlayer mediaPlayer = new MediaPlayer();

    private void load(int number) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(MusicList.getMusicArrayList().get(number).getMusicPath());
            mediaPlayer.prepare();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void play(int number) {
        if(mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        load(number);
        mediaPlayer.start();
    }

    private void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    private void stop() {
        mediaPlayer.stop();
    }

    private void resume() {
        mediaPlayer.start();
    }

    private void replay() {
        mediaPlayer.start();
    }

    private void moveNumberToPrevious() {
        if(number == 0) {
            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_reach_top),Toast.LENGTH_SHORT).show();
        }else {
            --number;
            play(number);
        }
    }

    private void moveNumberToNext() {
        if (number == MusicList.getMusicArrayList().size()-1) {
            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_reach_bottom),Toast.LENGTH_SHORT).show();
        }else {
            ++number;
            play(number);
        }
    }
}
